const { Service } = require('egg')
const { tableToList } = require('../utils/tools')

module.exports = class CreditService extends Service {
  /**
   *
   * @return {Array} *
   */
  async table() {
    const Cookie = this.ctx.state.Cookie
    const result = []
    const gradeUrl = `${this.ctx.state.baseUrl}/jsxsd/kscj/cjcx_list` // 成绩
    const planUrl = `${this.ctx.state.baseUrl}/jsxsd/pyfa/topyfamx` // 学生完成情况（体系）
    /* P1:学生完成情况（体系）；P3:成绩 */
    const P1 = this.ctx.curl(gradeUrl, {
      method: 'POST',
      data: {
        kksj: '',
        kcxz: '',
        kcmc: '',
        xsfs: 'all',
      },
      headers: {
        Cookie,
        'Content-Type': 'application/x-www-form-urlencoded',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36',
      },
      timeout: 10000,
    })
    const P2 = this.ctx.curl(planUrl, {
      method: 'GET',
      headers: {
        Cookie,
        // 'Content-Type': 'application/x-www-form-urlencoded',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36',
      },
      // data: {
      //   ndzydm: 'FD71BD5EA3CE47DCA2F6940EFE93D69B',
      //   jx0301zxjhid: '',
      // },
      timeout: 10000,
    })
    /* 将异步操作完成结果赋值：R1-P1;R2-P2 */
    const [R1, R2] = await Promise.all([P1, P2])
    if (R1.status === 200 && R2.status === 200) {
      try {
        // 按照课程编号获取到detial详细信息 detailInfo
        /* ['课程名称', '开设学期', '学分', '成绩'] */
        const tableDetail = tableToList(R1.data.toString(), '#dataList')
        const columnNeed = [3, 1, 7, 5] // 需要提取的列序号
        if (tableDetail.length === 0 || tableDetail[1][0] === '未查询到数据') return { result }
        const detailInfo = {}
        for (let i = 1; i < tableDetail.length; i++) {
          const term = tableDetail[i][2]
          if ((term in detailInfo) === false) { detailInfo[term] = [] }
          const tem = {
            N: '', T: '', C: '', G: '', S: '已获',
          }
          columnNeed.forEach((idx) => {
            if (idx === 3)tem.N = tableDetail[i][idx]
            if (idx === 1)tem.T = tableDetail[i][idx]
            if (idx === 7)tem.C = tableDetail[i][idx]
            if (idx === 5)tem.G = tableDetail[i][idx]
          })
          detailInfo[term] = tem
        }

        // 获取学习完成情况 oResult（直接存入result之中）
        const tableResult = tableToList(R2.data.toString(), '#mxh')
        if (tableResult.length === 0 || tableResult[1][0] === '未查询到数据') return { result }
        let oResult = {
          category: '', details: [], need: 0, has: 0,
        }
        for (let i = 0; i < tableResult.length; i++) {
          if (tableResult[i] && tableResult[i][0]) { // 检查 tableResult[i] 是否存在
            if (tableResult[i][0] !== '小计') {
              oResult.category = tableResult[i][0].replace(/\((.*?)\)/, '')
            }

            if (tableResult[i][0] === '小计') {
              oResult.need = tableResult[i][7]

              // 在将 oResult 添加到 result 之前，确保 oResult 是你期望的对象
              if (oResult && typeof oResult === 'object') {
                result.push(oResult)
              }

              oResult = {
                category: '', details: [], need: 0, has: 0,
              }
            }

            // 假设你希望每次循环都重置 oResult.has
            oResult.has = 0
          }
        }

        // 获取学习完成情况各性质下的课程id+课程属性 dInfo infoDetial
        const dInfo = {}
        const tempName = []
        let tempId = {}
        let j = 0
        for (let i = 2; i < tableResult.length; i++) {
          // 确保 tableResult[i] 和 tableResult[i-1] 都是有效的对象
          if (tableResult[i] && tableResult[i - 1]
              && (i === 2 || tableResult[i - 1][0] === '小计')
              && tableResult[i][0] !== '合计') {
            tempName[++j] = tableResult[i][0].replace(/\((.*?)\)/, '')
          }

          // 确保 tableResult[i] 是有效的对象，并且 tableResult[i][3] 不是空字符串
          if (tableResult[i] && tableResult[i][3] !== '') {
            tempId[tableResult[i][3]] = tableResult[i][2]
          }

          // 只有在当前项是 '小计' 时才更新 dInfo
          if (tableResult[i] && tableResult[i][0] === '小计') {
            dInfo[tempName[j]] = tempId
            tempId = {} // 重置 tempId 对象，以便收集下一个 '小计' 之前的 id
          }
        }

        const infoDetial = {}
        Object.keys(dInfo).forEach((key) => {
          const temp = []
          Object.keys(dInfo[key]).forEach((item) => {
            // console.log('dInfo[key][item]', dInfo[key][item]);
            // console.log('detailInfo[dInfo[key][item]]', detailInfo[dInfo[key][item]]);
            if (detailInfo[dInfo[key][item]])temp.push(detailInfo[dInfo[key][item]])
          })
          infoDetial[key] = temp
        })

        // 整合信息
        result.forEach((item) => {
          if (infoDetial[item.category])item.details = infoDetial[item.category]
          if (infoDetial[item.category.replace(/\((.*?)\)/, '')])item.details = infoDetial[item.category.replace(/\((.*?)\)/, '')]
        })
        let count = 0
        result.forEach((item) => {
          item.details.forEach((credit) => {
            count += Number(credit.C)
          })
          item.has = String(count)
          count = 0
        })
        return result
      } catch (err) {
        console.log(err)
      }
    }
    return result
  }

  /**
   * * 创新学分、素拓分、第二课堂分
   * @return {Array} *
   */
  async extra() {
    const Cookie = this.ctx.state.Cookie
    const apiUrl = `${this.ctx.state.baseUrl}/jsxsd/pyfa/cxxf_query`
    console.log('apiUrl', apiUrl)
    const res = await this.ctx.curl(apiUrl, {
      method: 'GET',
      headers: {
        Cookie,
        'Content-Type': 'application/x-www-form-urlencoded',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36',
      },
      timeout: 10000,
    })
    if (res.status === 200) {
      try {
        return tableToList(res.data.toString(), '#dataList')
      } catch (err) {
        return err
      }
    }
    return []
  }
}
